/**
 * 数据处理相关，放在mixin
 */
import { mapActions, mapState } from "vuex";
let moment = require("moment"); // 引入
export default {
  data() {
    return {
      connection: null, // 连接属性
      channel: null, // 频道属性
      messageList: [] // 消息列表
    };
  },
  computed: {
    ...mapState("user", ["user"])
  },
  methods: {
    ...mapActions("user", ["loadUser"]),
    ...mapActions("customerService", [
      "conService",
      "getHistory",
      "sendInformation",
      "getChanel",
      "readed"
    ]),
    // 处理历史消息
    dealHistory(data) {
      let beforeTime = null;
      let curentdata = new Date();
      let time = curentdata.toLocaleDateString();
      return data.map(item => {
        let showtime = "";
        if (!beforeTime || item.timestamp - beforeTime > 60) {
          var myDate = new Date(item.timestamp * 1000);
          var puttime = myDate.toLocaleDateString();
          if (puttime == time) {
            showtime = moment(item.timestamp * 1000).format("HH:mm:ss");
          } else {
            showtime = moment(item.timestamp * 1000).format(
              "YYYY-MM-DD HH:mm:ss"
            );
          }
        }
        beforeTime = item.timestamp;
        let params = {
          fromUserHeadImg: item.avatar,
          isItMe: item.direction == "to_service" ? true : false,
          contentType: 1,
          cid: item.cid,
          content: item.content,
          timestamp: item.timestamp,
          showtime: showtime
        };
        if (item.content.indexOf("<img") >= 0) {
          let srcReg = /src=[\'\"]?([^\'\"]*)[\'\"]?/i; //i忽略大小写 括号中内容放到内存中
          var src = item.content.match(srcReg);
          params.contentType = 3;
          params.content = src[1];
        }
        return params;
      });
    },
    //发送消息
    async sendMsg(data) {
      const params = {
        content: this.formData.content,
        fromUserHeadImg: this.userAvatar, //用户头像
        isItMe: true, //true此条信息是我发送的  false别人发送的
        timestamp: Date.parse(new Date()) / 1000,
        contentType: 1
      };
      if (data) {
        if (data.contentType == 2) {
          //发送语音
          params.content = data.content;
          params.contentType = data.contentType;
          params.contentDuration = data.contentDuration;
          params.anmitionPlay = false;
        } else if (data.contentType == 3) {
          //发送图片
          params.content = data.content;
          params.contentType = data.contentType;
          params.cid = data.cid;
        } else if (data.contentType==4) {
          //发送文件
          params.baseUrl = data.baseUrl;
          params.contentType = data.contentType;
          params.cid = data.cid;
          params.name = data.name;
        }
      } else if (this.formData.content == "") {
        //验证输入框书否为空字符传
        return;
      }
      if (!data.contentType) {
        let info = await this.sendInformation({
          content: this.formData.content,
          visiter_id: this.user.uuid,
          service_id: this.connection.service_id
        });
        params.cid = info.data;
      }
      this.messageList.push(params);

      this.$nextTick(() => {
        this.formData.content = "";
        // #ifdef MP-WEIXIN
        if (params.contentType == 1) {
          uni.pageScrollTo({
            scrollTop: 99999,
            duration: 0 //小程序如果有滚动效果 input的焦点也会随着页面滚动...
          });
        } else {
          setTimeout(() => {
            uni.pageScrollTo({
              scrollTop: 99999,
              duration: 0 //小程序如果有滚动效果 input的焦点也会随着页面滚动...
            });
          }, 150);
        }
        // #endif

        // #ifndef MP-WEIXIN
        uni.pageScrollTo({
          scrollTop: 99999,
          duration: 100
        });
        // #endif

        if (this.showFunBtn) {
          this.showFunBtn = false;
        }

        // #ifdef MP-WEIXIN
        if (params.contentType == 1) {
          this.mpInputMargin = true;
        }
        // #endif
        //h5浏览器并没有很好的办法控制键盘一直处于唤起状态 而且会有样式性的问题
        // #ifdef H5
        uni.hideKeyboard();
        // #endif
      });
    },
    async initData() {
      if (!this.user) {
        await this.loadUser();
      }
      const { data: connection, code, msg } = await this.conService({
        visiter_id: this.user.uuid,
        visiter_name: this.user.username
      });
      if (this.code == 1) {
        this.makeToast(msg);
      }
      this.connection = connection;
      const { data } = await this.getHistory({
        vid: this.user.uuid,
        service_id: connection.service_id
      });
      data.forEach(i=>{
        this.$set(i,'status','first')
      })
      this.channel = await this.getChanel({
        visiter_id: this.user.uuid,
        service_id: connection.service_id
      });
      if (data.length != 0) {
        this.messageList = this.dealHistory(data);
      }
      // 自动打招呼
      this.messageList.push({
        fromUserHeadImg: connection.avatar,
        isItMe: false,
        contentType: 1,
        cid: -1,
        content: connection.content,
        timestamp: Date.parse(new Date()) / 1000
      });
      setTimeout(() => {
        uni.pageScrollTo({
          scrollTop: 99999999,
          duration: 0
        });
      }, 200);
    }
  }
};
